package singleton;

class MyBlockingQueue {
    private int[] array;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    Object lock = new Object();

    public MyBlockingQueue(int capacity) {
        array = new int[capacity];
    }

    public void put(int key ) throws InterruptedException {
        synchronized (lock) {
            while (size == array.length) {
                // 队列已满, 阻塞
                lock.wait();
            }
            array[tail] = key;
            tail++;
            if (tail == array.length) {
                tail = 0;
            }
            size++;
            lock.notify();
        }
    }

    public int take() throws InterruptedException {
        synchronized (lock) {
            while (size == 0) {
                // 队列为空, 阻塞
                lock.wait();
            }
            int ret = array[head];
            head++;
            if (head == array.length) {
                head = 0;
            }
            size--;
            lock.notify();
            return ret;
        }
    }

}
public class demo7_MyBlockingQueue {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread t1 = new Thread(() -> {
           int n = 0;
           while (true) {
               try {
                   queue.put(n);
                   System.out.println("生产了: " + n);
                   n++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread t2 = new Thread (() -> {
           int n = 0;
           while (true) {
               try {
                   n = queue.take();
                   System.out.println("消费了: " + n);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        t1.start();
        t2.start();
    }
}
